package org.lanqiao.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lanqiao.util.BeanToJsonWriter;
import org.lanqiao.util.SqlUtil;
import org.lanqiao.vo.JsonResultVo;

@WebServlet("/order/buy")
public class AddOrderServlet extends  HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取购买商品Ids
		String [] proids=  request.getParameterValues("proids");
		String id =request.getParameter("id");
		String username =request.getParameter("username");

		String name =request.getParameter("name");
		String receiver =request.getParameter("receiver");
		String telphone =request.getParameter("telphone");
		String address =request.getParameter("address");
		String price =request.getParameter("price");
		//插入订单
		JsonResultVo<String>   jsonResult;
		try{
			String sql="insert into `order`  values(?,?,?,?,?,?,?,now())";
			//应该开启事务
			SqlUtil.executeUpdate(sql, id,username,name,receiver,telphone,address,price);
			//构建一个更新语句
			StringBuilder sql2 =new StringBuilder("update 	car  set orderid=?  where id  in (  ");
			for(int i =0;i<proids.length;i++){
				if(i==proids.length-1){
					sql2.append(proids[i]);
				}else{
					sql2.append(proids[i]).append(",");
				}
			
			}
			sql2.append("  )   ");
			//SqlUtil提交事务 
			//可变参数同时传递,一个数值和一个数组 会有识别问题，所有把参数拼接到Sql语句中了
			SqlUtil.executeUpdate(sql2.toString(),id);
			jsonResult =new JsonResultVo<String>("200","提交成功",id);
		}
		catch(Exception ex){
			jsonResult =new JsonResultVo<String>("500","异常错误:"+ex.getMessage(),id);
			ex.printStackTrace();
			
		}
		
		BeanToJsonWriter.write(response, jsonResult);
	}
}
